<?php
namespace app\api\model\foodcash;

use app\common\model\ShopClerk as ShopClerkModel;
use think\facade\Cache;

/**
 * 店员模型
 */
class ShopClerk extends ShopClerkModel
{
	/**
     * 隐藏字段
     */
    protected $hidden = [];
    
    /**
     * 获取用户信息
     */
    public static function getDetail($token)
    {
    	$data = Cache::get($token);//获取登录数据
    	if(!is_null($data)){
            return self::get($data['shop_clerk_id'],['shop']);
    	}
    	return false;
    }

   /**
     * 登录
     */
    public function login($data)
    {
    	if(!$user = self::withoutGlobalScope()->with(['shop'])->where([
			'mobile' => $data['user_name'],
			'pwd' => hema_hash($data['password'])
		])->find()){
			$this->error = '用户不存在，或密码错误';
			return false;
		}
		if($user['user_id'] == 0){
		    $this->error = '请先用该身份在商家助手登录一次';
			return false;
		}
		$user['user'] = User::withoutGlobalScope()->where('user_id',$user['user_id'])->find();
        // 生成token (session3rd)
        $token = $this->token($user['shop_clerk_id']);
        $user['token'] = $token;
        // 记录缓存, 7天
        Cache::set($token, $user, 86400 * 7);
		return $user;
    }
	
	/**
     * 生成用户认证的token
     */
    private function token($shop_clerk_id)
    {
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'clerk_token_salt';
        return md5("{$shop_clerk_id}_{$timeStamp}_{$salt}");
    }
	
	/**
	 * 修改登录密码
	 */
	public function renew($user)
	{
		if($model = $this->where(['mobile' => $user['user_name']])->find()){
			$model->pwd = hema_hash($user['password']);
			return $model->save();
		}
		$this->error = '用户不存在';
		return false;
	}
}
